package com.taplinker.client.im.rpc;

import java.util.ArrayList;
import java.util.List;

import android.text.TextUtils;

import com.taplinker.client.im.domain.ImDataCenter;
import com.taplinker.client.im.protocol.TapLinkerConversation;
import com.taplinker.client.im.rpc.body.Cmd004Rep;
import com.taplinker.client.im.rpc.body.Cmd004Req;
import com.taplinker.client.im.rpc.body.ConvertUtil;
import com.taplinker.core.rpc.Result;
import com.taplinker.core.util.LogUtil;
import com.taplinker.core.util.json.JsonUtil;

public class Cmd004 extends SimpleSocketCommand<Cmd004Req>{
	public Cmd004(String source,int recordNo,String order,int pageSize) {
		body = new Cmd004Req();
		body.setOrder(order);
		body.setPageSize(pageSize);
		body.setRecordNo(recordNo);
		body.setSource(source);
	}
	
	public Cmd004(int recordNo,int pageSize) {
		body = new Cmd004Req();
		body.setOrder("desc");
		body.setPageSize(pageSize);
		body.setRecordNo(recordNo);
	}
	
	public Cmd004(String source ,boolean more) {
		if(!more) {
			ImDataCenter.getInstance().getPrivQueue().clear();
		}
		body = new Cmd004Req();
		body.setOrder("desc");
		body.setPageSize(ImDataCenter.PAGE_SIZE);
		body.setRecordNo(ImDataCenter.getInstance().getPrivQueue().size());
		if(!TextUtils.isEmpty(source)) {
			body.setSource(source);
		}
	}
	
	public Cmd004(String source) {
		this(source, false);
	}
	
	@Override
	public void yes(Result result) {
		super.yes(result);
		List<Cmd004Rep> list = JsonUtil.jsonToList(((IMMessageResponse) result.object).getMessage().getBody(), Cmd004Rep.class);
		
		List<TapLinkerConversation> queue = new ArrayList<TapLinkerConversation>();
		for(Cmd004Rep value : list) {
			TapLinkerConversation conversation = ConvertUtil.convertToConversation(value);
			conversation.setQueueType(TapLinkerConversation.PRIVATE_QUEUE);
			queue.add(conversation);
		}
		ImDataCenter.getInstance().addAllPrivateQueue(queue);
		if(list == null || list.size() < 1) {
			ImDataCenter.getInstance().noticeListener(ImDataCenter.CONVERSATION_NO_MORE);
		}
		LogUtil.d("004", "receive");
	}

	@Override
	protected String getCommand() {
		return "004";
	}
}
